package com.lapelittle.framework.service;

import com.lapelittle.framework.entity.SysUser;
import com.lapelittle.framework.exception.BusinessException;
import com.lapelittle.framework.mapper.SysUserMapper;
import com.lapelittle.framework.model.UserUpdateRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private SysUserMapper userMapper;
    
    @Autowired
    private EmailService emailService;
    
    public boolean updateUser(Long userId, UserUpdateRequest request) {
        // 检查手机号唯一性
        if (request.getMobile() != null && !request.getMobile().isEmpty()) {
            SysUser existingUser = userMapper.findByMobileExcludeSelf(request.getMobile(), userId);
            if (existingUser != null) {
                throw new BusinessException("手机号已被使用");
            }
        }
        
        // 检查邮箱唯一性
        if (request.getEmail() != null && !request.getEmail().isEmpty()) {
            // 获取当前用户信息
            SysUser currentUser = userMapper.findById(userId);
            if (currentUser != null && !request.getEmail().equals(currentUser.getEmail())) {
                // 邮箱发生变化时，需要验证邮箱唯一性
                SysUser existingUser = userMapper.findByEmailExcludeSelf(request.getEmail(), userId);
                if (existingUser != null) {
                    throw new BusinessException("邮箱已被使用");
                }
            }
        }
        
        SysUser user = new SysUser();
        user.setId(userId);
        user.setNickname(request.getNickname());
        user.setMobile(request.getMobile());
        user.setEmail(request.getEmail());
        user.setAvatar(request.getAvatar());
        
        return userMapper.updateUser(user) > 0;
    }

    public void sendEmailCode(Long userId, String email) {
        if (email == null || email.isEmpty()) {
            throw new BusinessException("邮箱不能为空");
        }
        
        // 验证邮箱是否被其他用户使用
        SysUser existingUser = userMapper.findByEmailExcludeSelf(email, userId);
        if (existingUser != null) {
            throw new BusinessException("该邮箱已被其他用户使用");
        }
        
        // 发送验证码
        emailService.sendCode(email);
    }

    public boolean verifyEmailCode(Long userId, String email, String code) {
        if (email == null || email.isEmpty()) {
            throw new BusinessException("邮箱不能为空");
        }
        
        if (code == null || code.isEmpty()) {
            throw new BusinessException("验证码不能为空");
        }
        
        // 验证邮箱是否被其他用户使用
        SysUser existingUser = userMapper.findByEmailExcludeSelf(email, userId);
        if (existingUser != null) {
            throw new BusinessException("该邮箱已被其他用户使用");
        }
        
        // 验证验证码
        return emailService.verifyCode(email, code);
    }
} 